from typing import Optional

from ninja import FilterSchema, Field, ModelSchema
from django.db.models import Q

from models.models import WaterCardRecord


class WaterCardRecordFilterSchema(FilterSchema):
    """用户订单筛选"""
    operator: Optional[str] = Field(default=None, description="操作人",
                                    q=["user__nickname__contains", "user__openid__contains"])
    name: Optional[str] = Field(default=None, description="任务名称", q="name__icontains")
    card_type: Optional[int] = Field(default=None, description="类型")
    time: Optional[dict] = None

    def filter_time(self, value: dict):
        if not value:
            return Q()
        if value.get('start') and not value.get('end'):
            return Q(time__gt=value.get('start'))
        if not value.get('start') and value.get('end'):
            return Q(time__lt=value.get('end'))
        if value.get('start') and value.get('end'):
            return Q(time__gt=value.get('start'), time__lt=value.get('end'))
        return Q()


class WaterCardRecordResponseSchema(ModelSchema):
    class Config:
        model = WaterCardRecord
        model_fields = "__all__"
